# -*- coding: utf-8 -*-
'''
    :file: Sysmessage.py
    :author: -Farmer
    :url: https://blog.farmer233.top
    :date: 2021/04/07 12:27:23
'''
from flask.globals import current_app
import psutil
from time import sleep
from app.models import LogMsg
from app.extensions import db


# 获取系统基本信息（通用）
class BaseMsg():
    def __init__(self) -> None:
        pass
    
    def get_cpu_core(self):
        # 获取服务器核心数
        try:
            core_msg = {
                "physical": psutil.cpu_count(),
                "logical": psutil.cpu_count(logical=True)
            }
            return core_msg
        except Exception as e:
            current_app.logger.warning(e)
            raise ValueError('获取cpu信息失败')
        
    def get_memory(self):
        # 获取服务器内存信息
        try:
            mem = psutil.virtual_memory()
            mry_msg = {
                "total": mem.total,
                'available': mem.available,
                "percent": mem.percent,
                "used": mem.used,
                "free": mem.free
            }
            return mry_msg
        except Exception as e:
            current_app.logger.warning(e)
            raise ValueError('获取内存信息失败')
    
    def get_disk_msg(self):
        # 获取服务器硬盘信息
        try:
            disks = psutil.disk_partitions()
            disk_msg  = []
            for item in disks:
                temp = psutil.disk_usage(item.mountpoint)
                disk_msg.append({
                    "mountPoint": item.mountpoint,
                    "fstype":  item.fstype,
                    "disk_usage": {
                        "total": temp.total,
                        "used": temp.used,
                        "free": temp.free,
                        "percent": temp.percent
                    }
                })
            return disk_msg
        except Exception as e:
            raise ValueError("获取硬盘信息失败")

    def get_network_config(self):
        # 获取系统网络信息
        psutil.net_if_addrs()

# 获取系统动态信息
class DynamicMsg(BaseMsg):
    def get_cpu_rate(self):
        # 获取cpu使用率
        data = psutil.cpu_percent(interval=1, percpu=True)
        return data

    def _get_key(self):
        key_info = psutil.net_io_counters(pernic=True).keys()
        recv = {}
        sent = {}

        for key in key_info:
            recv.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_recv)
            sent.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_sent)

        return key_info, recv, sent


    def _get_rate(self, func):
        key_info, old_recv, old_sent = func()
        sleep(1) # 通过暂停一秒，计算流量速率
        key_info, now_recv, now_sent = func()
        net_in = {}
        net_out = {}

        for key in key_info:
            net_in.setdefault(key, float('%.2f' %((now_recv.get(key) - old_recv.get(key)) / 1024)))
            net_out.setdefault(key, float('%.2f' %((now_sent.get(key) - old_sent.get(key)) / 1024)))

        return key_info, net_in, net_out


    def get_network_msg(self):
        # 获取网络流量信息
        key_info, net_in, net_out = self._get_rate(self._get_key)
        network_rate = []
        for key in key_info:
            network_rate.append({
                key: {
                    "in": f'{net_in.get(key)}',
                    "out": f'{net_out.get(key)}'
                }
            })

        return network_rate

    def get_dynamic_msg(self):
        # 统一获取并返回动态信息
        res_data = {
            "cpu_core_rate": self.get_cpu_rate(),
            "network_rate": self.get_network_msg()
        }
        return res_data

# 系统日志信息
class SystemLogMsg():
    def __init__(self) -> None:
        pass
    
    def get(page:int=1, per_page:int=30):
        # 分页获取日志
        data = LogMsg.query.paginate(page=page, per_page=per_page)
        return data
        